package com.github.hgkmail.hello.fsm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.squirrelframework.foundation.fsm.annotation.ContextInsensitive;
import org.squirrelframework.foundation.fsm.impl.AbstractStateMachine;

//@ContextInsensitive
public class ATMStateMachine extends AbstractStateMachine<ATMStateMachine, ATMStateMachine.ATMState, String, ATMContext> {
    private static final Logger logger = LoggerFactory.getLogger(ATMStateMachine.class);

    public static final String EV_CONNECTED = "Connected";
    public static final String EV_LOAD_FAIL = "LoadFail";
    public static final String EV_RESTART = "Restart";

    //State Enum
    public enum ATMState {
        Idle(1), Loading(2), OutOfService(3), Disconnected(4), InService(5);

        private final int value;

        private ATMState(int value) {
            this.value = value;
        }

        public ATMState valueOf(int val) {
            for (ATMState one:ATMState.values()) {
                if (one.value==val) {
                    return one;
                }
            }
            return null;
        }
    }//enum

    void postConstruct() {
        logger.info("ATMStateMachine postConstruct");
    }

    public void entryIdle(ATMState from, ATMState to, String event, ATMContext context) {
        logger.info("entryIdle: {}--{}-->{} {}", from, event, to, context);
    }

    public void exitIdle(ATMState from, ATMState to, String event, ATMContext context) {
        logger.info("exitIdle: {}--{}-->{} {}", from, event, to, context);
    }

    public void transitFromIdleToLoadingOnConnected(ATMState from, ATMState to, String event, ATMContext context) {
        logger.info("transitFromIdleToLoadingOnConnected: {}--{}-->{} {}", from, event, to, context);
    }

    public void transitFromLoadingToOutOfServiceOnLoadFail(ATMState from, ATMState to, String event, ATMContext context) {
        logger.info("transitFromLoadingToOutOfServiceOnLoadFail: {}--{}-->{} {}", from, event, to, context);
    }

    public void transitFromOutOfServiceToLoadingOnRestart(ATMState from, ATMState to, String event, ATMContext context) throws Exception {
        logger.info("transitFromOutOfServiceToLoadingOnRestart: {}--{}-->{} {}", from, event, to, context);
    }

    protected void afterTransitionCausedException(ATMState from, ATMState to, String event, ATMContext context) {
        logger.info("afterTransitionCausedException: {}--{}-->{} {}", from, event, to, context);
        Throwable targeException = getLastException().getTargetException();
        logger.error("ex: ", targeException);
    }

}
